package controllers;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import models.MMSMO;
import play.mvc.Controller;

public class MMS extends Controller {
	public static void submit(String toAddress) throws Exception {
		MMSMO mensagem = new MMSMO();

		mensagem.setDateTime(new Date());
		mensagem.setToAddress(toAddress);

		mensagem.setContent(getContent());

		mensagem.insert();

		MimeMessage mimeMessage = new MimeMessage(Session
				.getDefaultInstance(new Properties()),
				new ByteArrayInputStream(mensagem.getContent()
						.getBytes("ASCII")));

		Address[] from = mimeMessage.getFrom();

		mensagem.setFrom(from[0].toString());
		mensagem.setSubject(mimeMessage.getSubject());

		mensagem.update();
	}

	private static String getContent() throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		byte[] buf = new byte[16384];
		int nRead;

		while (-1 != (nRead = request.body.read(buf)))
			baos.write(buf, 0, nRead);

		return new String(baos.toByteArray(), "ASCII");
	}
}
